import type { FormInstance } from 'antd';
import { Button, Space } from 'antd';
import { memo, useMemo } from 'react';
import { TSubmitter } from './interface';

function Submitter(props: {
  queryFilterFormInstance: FormInstance;
  submitter?: TSubmitter;
  hiddenReset: boolean;
}) {
  const { queryFilterFormInstance, submitter, hiddenReset } = props;

  // 重置
  const handleReset = () => {
    queryFilterFormInstance.resetFields();
    submitter?.onReset?.();
  };

  // 提交
  const handleSubmit = () => {
    queryFilterFormInstance
      .validateFields()
      .then((values) => {
        // console.log('---Submitter--handleSubmit----values--:', values);
        submitter?.onSubmit(values);
      })
      .catch((err) => {
        console.log('--queryFilter---handleSubmit--err---:', err);
      });
  };

  const submitNode = useMemo(() => {
    if (!queryFilterFormInstance) return;
    // const { resetButtonProps = {}, submitButtonProps = {}, render = null } = submitter;
    if (typeof submitter?.render === 'function') {
      return submitter.render(queryFilterFormInstance);
    }

    return (
      <Space direction="horizontal">
        {!hiddenReset && (
          <Button
            onClick={handleReset}
            type="default"
            {...submitter?.resetButtonProps}
          >
            {submitter?.resetText || '重置'}
          </Button>
        )}
        <Button
          onClick={handleSubmit}
          type="primary"
          {...submitter?.submitButtonProps}
        >
          {submitter?.submitText || '查询'}
        </Button>
      </Space>
    );
  }, [submitter, queryFilterFormInstance]);

  return <>{submitNode}</>;
}

export default memo(Submitter);
